package com.source.lightfowl.basedata.service.impl;

import java.io.File;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.source.lightfowl.DTO.ToMarketDownloadDTO;
import com.source.lightfowl.VO.ToMarketCurveVO;
import com.source.lightfowl.basedata.dao.StallsDao;
import com.source.lightfowl.basedata.dao.ToMarketDao;
import com.source.lightfowl.basedata.entity.ToMarket;
import com.source.lightfowl.basedata.service.ToMarketService;

import com.source.lightfowl.constant.ImageCatalogue;
import com.source.lightfowl.handler.MyException;
import com.source.lightfowl.labelingRecord.dao.RecordDao;
import com.source.lightfowl.utils.IdWorker;
import com.source.lightfowl.utils.ImageUtil;
import com.source.lightfowl.utils.QRCodeUtil;
import com.source.lightfowl.utils.StatusCode;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: cxy
 * @Description: 去向市场
 */
@Service
public class ToMarketServiceImpl implements ToMarketService {

    @Autowired
    private ToMarketDao toMarketDao;
    @Autowired
    private RecordDao recordDao;
    @Autowired
    private StallsDao stallsDao;
    @Autowired
    private IdWorker idWorker;

    @Override
    public List<ToMarket> findAll(int state) {
        return toMarketDao.findByState(state);
    }

    @Override
    public List<Object> findAllDTO() {
        List<ToMarket> toMarkets = toMarketDao.findByState(1);
        List<Object> list = new ArrayList<>();
        for (ToMarket toMarket :
                toMarkets) {
            ToMarketDownloadDTO toMarketDownloadDTO = new ToMarketDownloadDTO();
            BeanUtils.copyProperties(toMarket, toMarketDownloadDTO);
            String addr = "";
            if (toMarket.getProvince() != null)
                addr += toMarket.getProvince();
            if (toMarket.getCity() != null)
                addr += toMarket.getCity();
            if (toMarket.getDistrict() != null)
                addr += toMarket.getDistrict();
            if (toMarket.getAddr() != null)
                addr += toMarket.getAddr();
            toMarketDownloadDTO.setAddr(addr);
            list.add(toMarketDownloadDTO);
        }
        return list;
    }

    @Override
    public void save(List<Object> list, HttpServletRequest request) {
        List<ToMarket> toMarkets = new ArrayList<>();
        for (Object object :
                list) {
            ToMarket toMarket = new ToMarket();
            BeanUtils.copyProperties((ToMarketDownloadDTO) object, toMarket);
            toMarket.setId(idWorker.nextId() + "");
            toMarket.setState(1);
            toMarkets.add(toMarket);
        }
        toMarketDao.saveAll(toMarkets);
    }

    @Override
    public Page<ToMarket> findAllPage(int state, int page, int size) {
        PageRequest pageRequest = PageRequest.of(page - 1, size);
        return toMarketDao.findByState(state, pageRequest);
    }

    @Override
    public Optional<ToMarket> findById(String id) {
        return toMarketDao.findByIdAndStateNot(id, 0);
    }

    @Override
    public void save(ToMarket toMarket) {
        toMarket.setId(idWorker.nextId() + "");
        toMarketDao.save(toMarket);
    }

    @Override
    public void save(ToMarket toMarket, MultipartFile markCodeFile, MultipartFile stallCodeFile, HttpServletRequest request) {
        toMarket.setId(idWorker.nextId() + "");
        if (markCodeFile != null) {
            String url = upload(markCodeFile, request);
            toMarket.setMarkCode(url);
            try {
                String markCodeAnalysis = QRCodeUtil.decode(ImageUtil.multipartFileToFile(markCodeFile));
                toMarket.setMarkCodeAnalysis(markCodeAnalysis);
            } catch (Exception e) {
                throw new MyException(StatusCode.ANALYSE_IMG_ERROR, "解析二维码图片失败");
            }
        }
        if (stallCodeFile != null) {
            toMarket.setStallCode(upload(stallCodeFile, request));
            try {
                String stallCodeAnalysis = QRCodeUtil.decode(ImageUtil.multipartFileToFile(stallCodeFile));
                toMarket.setStallCodeAnalysis(stallCodeAnalysis);
            } catch (Exception e) {
                throw new MyException(StatusCode.ANALYSE_IMG_ERROR, "解析二维码图片失败");
            }
        }
        toMarketDao.save(toMarket);
    }

    @Override
    public String upload(MultipartFile file, HttpServletRequest request) {
//        String loginName = (String)request.getAttribute("loginName");
//        System.out.println("loginName: " + loginName);
        String s = null;
        try {
            s = ImageUtil.saveImage(file, ImageCatalogue.ToMarket_Catalogue);
        } catch (Exception e) {
            System.out.println("图片保存异常");
            System.out.println(e.getMessage());
        }
        return s;
    }

    @Override
    public void update(ToMarket toMarket) {
        ToMarket oldToMarket = toMarketDao.findById(toMarket.getId()).get();
        //更新市场二维码
        try {
            if (!oldToMarket.getMarkCode().equals(toMarket.getMarkCode())) {
                ImageUtil.delete(toMarket.getMarkCode(), ImageCatalogue.ToMarket_Catalogue);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //更新市场档口二维码
        try {
            if (!oldToMarket.getStallCode().equals(toMarket.getStallCode())) {
                ImageUtil.delete(toMarket.getStallCode(), ImageCatalogue.ToMarket_Catalogue);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        toMarketDao.save(toMarket);
    }

    @Override
    public void update(ToMarket toMarket, MultipartFile markCodeFile, MultipartFile stallCodeFile, HttpServletRequest request) {
        ToMarket oldToMarket = toMarketDao.findById(toMarket.getId()).get();
        //更新市场二维码
        try {
            if (markCodeFile!= null) {
                toMarket.setMarkCode(upload(markCodeFile, request));
                try {
                    String markCodeAnalysis = QRCodeUtil.decode(ImageUtil.multipartFileToFile(markCodeFile));
                    toMarket.setMarkCodeAnalysis(markCodeAnalysis);
                } catch (Exception e) {
                    throw new MyException(StatusCode.ANALYSE_IMG_ERROR, "解析二维码图片失败");
                }
                ImageUtil.delete(toMarket.getMarkCode(), ImageCatalogue.ToMarket_Catalogue);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //更新市场档口二维码
        try {
            if (stallCodeFile!= null) {
                toMarket.setStallCode(upload(stallCodeFile, request));
                try {
                    String stallCodeAnalysis = QRCodeUtil.decode(ImageUtil.multipartFileToFile(stallCodeFile));
                    toMarket.setStallCodeAnalysis(stallCodeAnalysis);
                } catch (Exception e) {
                    throw new MyException(StatusCode.ANALYSE_IMG_ERROR, "解析二维码图片失败");
                }
                ImageUtil.delete(toMarket.getStallCode(), ImageCatalogue.ToMarket_Catalogue);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        toMarketDao.save(toMarket);
    }

    @Override
    public void deleteById(String id) {
        ToMarket toMarket = toMarketDao.findById(id).get();
        toMarket.setState(0);
        deletePic(id);
        toMarketDao.save(toMarket);
    }

    @Override
    public void deleteBatch(String ids) {
        ArrayList<String> list = new ArrayList(Arrays.asList(ids.split(",")));
        for (String id :
                list) {
            deletePic(id);
        }
        toMarketDao.changeBatch(0, list);
    }

    @Override
    public void changeBatch(int state, String ids) {
        ArrayList<String> list = new ArrayList(Arrays.asList(ids.split(",")));
        toMarketDao.changeBatch(state, list);
    }

    @Override
    public List<ToMarket> findByNameLike(String name) {
        return toMarketDao.findByNameLike(1, name);
    }

    @Override
    public List<ToMarket> findByStallNameLike(String stallName) {
        return toMarketDao.findByStallNameLike(1, stallName);
    }

    @Override
    public List<String> findByProvince(String province) {
        return toMarketDao.findCity(1, province);
    }

    @Override
    public List<String> findByCity(String province, String city) {
        return toMarketDao.findDistrict(1, province, city);
    }

    @Override
    public List<ToMarket> findByDistrict(String province, String city, String district) {
        return toMarketDao.findMarket(1, province, city, district);
    }

    @Override
    public ToMarketCurveVO stallsCount(String slaughterHouseId) {
        List<String> stallsIdList = stallsDao.findBySlaughterHouseId(1, slaughterHouseId);
        List<String> toMarkIdList = recordDao.findByStallsId(stallsIdList);
        List<Map<Object, Object>> result = toMarketDao.stallsCount(toMarkIdList, 1);
        List<String> monthList = new ArrayList<>();
        List<Integer> stallsList = new ArrayList<>();
        ToMarketCurveVO resultVO = new ToMarketCurveVO();
        for (Map<Object, Object> mapList : result) {
            ToMarketCurveVO vo = new ToMarketCurveVO();
            monthList.add(mapList.get("createMonth").toString());
            String str = mapList.get("total").toString();// 需要取整数和小数的字符串
            Pattern p = Pattern.compile("(\\d+)");// 控制正则表达式的匹配行为的参数(整数)
            Matcher m = p.matcher(str);//Matcher类的构造方法也是私有的,不能随意创建,只能通过Pattern.matcher(CharSequence input)方法得到该类的实例.
            if (m.find()) {
                str = m.group(1) == null ? "" : m.group(1);//如果有整数相匹配
            } else {
                str = "0";//如果没有小数和整数相匹配,即字符串中没有整数和小数，就设为空
            }
            stallsList.add(Integer.valueOf(str));
        }
        resultVO.setMonth(monthList);
        resultVO.setStalls(stallsList);
        return resultVO;
    }

    private void deletePic(String id) {
        Optional<ToMarket> optional = toMarketDao.findById(id);
        if (optional.isPresent()) {
            ToMarket toMarket = optional.get();
            String mag1 = toMarket.getStallCode();
            String mag2 = toMarket.getMarkCode();
            if (mag1 != null && !mag1.equals(""))
                ImageUtil.delete(mag1, ImageCatalogue.ToMarketStallCode_Catalogue);
            if (mag2 != null && !mag2.equals(""))
                ImageUtil.delete(mag2, ImageCatalogue.ToMarketMarkCode_Catalogue);
        }
    }
}
